package com.zh.mycommon.util;

import com.zh.mycommon.value.Tuple2;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author Zhou
 * @date 20:17 2024/10/16
 */

public final class MyImageUtil {

    /**
     * @param image1    图片1
     * @param image2    图片2
     * @param alignType 对齐方式：-1自动、0水平、1垂直
     * @return 合并后的Image
     */
    public static BufferedImage joint(BufferedImage image1, BufferedImage image2, int alignType) {
        assert image1 != null;
        assert image2 != null;

        //水平方式size
        int totalWidth = image1.getWidth() + image2.getWidth();
        int maxHeight = Math.max(image1.getHeight(), image2.getHeight());
        var sizeByHorizontal = new Tuple2<>(totalWidth, maxHeight);
        //垂直方式size
        int totalHeight = image1.getHeight() + image2.getHeight();
        int maxWidth = Math.max(image1.getWidth(), image2.getWidth());
        var sizeByVertical = new Tuple2<>(maxWidth, totalHeight);

        var perimeterV = sizeByVertical.v1() + sizeByVertical.v2();
        var perimeterH = sizeByHorizontal.v1() + sizeByHorizontal.v2();

        assert alignType * alignType <= 1;

        //是否垂直拼接
        boolean vertical = alignType == -1 ? (perimeterV < perimeterH) : (alignType == 1);

        var size = vertical ? sizeByVertical : sizeByHorizontal;
        BufferedImage combinedImage = new BufferedImage(size.v1(), size.v2(), BufferedImage.TYPE_INT_RGB);
        // 使用Graphics2D来绘制
        Graphics2D g = combinedImage.createGraphics();

        //垂直方式 or 水平方式
        if (vertical) {
            // 绘制第一张图片
            g.drawImage(image1, 0, 0, null);
            // 绘制第二张图片，起始位置为第一张图片的下边
            g.drawImage(image2, 0, image1.getHeight(), null);
        } else {
            // 绘制第一张图片
            g.drawImage(image1, 0, 0, null);
            // 绘制第二张图片，起始位置为第一张图片的右侧
            g.drawImage(image2, image1.getWidth(), 0, null);
        }
        // 清理资源
        g.dispose();
        return combinedImage;
    }

    /**
     * @param picture1 图片1
     * @param picture2 图片2
     * @param outPath  要保存的文件路径
     * @return 合并后的File
     */
    public static File joint(File picture1, File picture2, String outPath) {
        final BufferedImage image1;
        final BufferedImage image2;
        try {
            image1 = ImageIO.read(picture1);
            image2 = ImageIO.read(picture2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            //合并图像
            BufferedImage outImage = joint(image1, image2, -1);

            // 保存合并后的图片到文件
            var outFile = new File(outPath);
            ImageIO.write(outImage, "jpg", outFile);
            return outFile;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
